<template>
  <div class="classifyxq">
    <my-header v-if="!showSearch">
      <template #left>
        <van-icon name="arrow-left" @click="$router.back()" />
      </template>
      <template #center> 分类商品 </template>
      <template #right>
        <van-icon name="search" @click="showSearch = !showSearch" />
      </template>
    </my-header>
    <van-search
      v-else
      v-model="inputVal"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="showSearch = !showSearch"
    />
    <div class="content">
      <my-cart
        v-for="(item, index) in showList"
        :key="index"
        :itemObj="item"
      ></my-cart>
    </div>
    <van-popup v-model:show="showSearch" position="top">
      <div class="pop-content">
        <p><span>历史记录</span><span style="color: red" @click="$store.commit('removeHistory')">全部删除</span></p>
        <van-tag v-for="(item,index) in historyList" :key="index"
          closeable
          size="large"
          type="primary"
          @close="$store.commit('delHistory',index)"
          @click="checkFtn(item)"
        >
          {{item}}
        </van-tag>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from "vue";
import myHeader from "../../components/myHeader.vue";
import { getGoods } from "@/api/home/index";
import MyCart from "../../components/myCart.vue";
import { useStore } from "vuex";
export default {
  components: { myHeader, MyCart },
  setup() {
    const { state, commit } = useStore();
    const data = reactive({
      allList: [], // 所有的商品
      showList: [], // 展示的数据
      showSearch: false, // 是否显示搜索
      inputVal: "",
      historyList: computed(() => state.history),
    });
    getGoods().then((res) => {
      data.allList = res.data;
      data.showList = data.allList;
    });
    const onSearch = () => {
      // 搜索事件
      data.showList = data.allList.filter((item) =>
        item.name.includes(data.inputVal)
      );
      if (data.inputVal) {
        commit("saveHistory", data.inputVal);
      }
      data.showSearch = false;
    };
    const checkFtn = (val) => { // 点击历史记录的函数
        data.inputVal = val;
        onSearch();
    }
    return {
      ...toRefs(data),
      onSearch,
      checkFtn
    };
  },
};
</script>
<style lang="scss" scoped>
.classifyxq {
  height: 100%;
  .van-search {
    padding: 8px;
    position: relative;
    z-index: 9999;
  }
  .content {
    height: calc(100% - 50px);
    overflow: auto;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
}
.pop-content {
  margin-top: 50px;
  padding: 10px 15px;
  p {
    font-size: 14px;
    display: flex;
    justify-content: space-between;
  }
  .van-tag{
    margin: 10px 10px 0 0;
  }
}
</style>